import AsyncStorage from "@react-native-async-storage/async-storage";
import { type Service, type Characteristic } from "react-native-ble-plx";
import iconv from "@vscode/iconv-lite-umd";
import toast from "./toast";
const Buffer = require("@craftzdog/react-native-buffer").Buffer;
export const setStorageData = async (key: string, value: string) => {
  return await AsyncStorage.setItem(key, value);
};
export const getStorageData = async (key: string) => {
  return await AsyncStorage.getItem(key);
};
export const rmStorageData = async (key: string) => {
  return await AsyncStorage.removeItem(key);
};

// 判断目标设备是否具有 ffe0服务
export const determineCurrentDevice = (services: Service[]) => {
  for (let item of services) {
    if (item.uuid.match(/ffe0/i)) {
      return item;
    }
  }
  return false;
};
export function stringToGBKHex(value = "") {
  // 将字符串转换为 Buffer
  const buffer = iconv.encode(value, "gbk");

  // 将 Buffer 转换为十六进制字符串
  let hexString = "";
  for (let i = 0; i < buffer.length; i++) {
    const hex = buffer[i].toString(16).toUpperCase();
    hexString += hex.length === 1 ? "0" + hex : hex;
  }
  return hexString;
}
// 写入特征值
export const WritableWithResponse = (
  characteristic: Characteristic,
  value: string
) => {
  return new Promise((resolve) => {
    const Subscription = characteristic.monitor((err, characteristic) => {
      if (err && err.reason) {
        toast(err.reason, 5 * 1000);
        return Subscription.remove();
      }
      if (characteristic?.value) {
        resolve(
          Buffer.from(JSON.stringify(characteristic.value), "base64").toString(
            "hex"
          )
        );
      }
      return Subscription.remove();
    });
    characteristic.writeWithResponse(
      Buffer.from(value, "hex").toString("base64")
    );
  });
};
